package com.cch.demo.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cch.demo.sys.domain.Dept;
import com.cch.demo.sys.domain.Permission;
import com.cch.demo.sys.domain.User;
import com.cch.demo.sys.service.PermissionService;
import com.cch.demo.sys.service.RoleService;
import com.cch.demo.sys.util.*;
import com.cch.demo.sys.vo.DeptVo;
import com.cch.demo.sys.vo.PermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("menu")
public class MenuContoller {

    @Resource
    private PermissionService permissionServiceImpl;

    @Resource
    private RoleService roleServiceImpl;



    /**
     * 页面左边的菜单树
     * @param permissionVo
     * @return
     */
    @RequestMapping("loadIndexLeftMenuJson")
    public DataGridView loadIndexLeftPermissionJson(PermissionVo permissionVo){

        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        //设置只能查询菜单
        queryWrapper.eq("type","menu");
        queryWrapper.eq("available", Constast.AVAILABLE_TRUE);
        User user = (User) WebUtils.getSession().getAttribute("user");
        List<Permission> list= null;
        if(user.getType() == Constast.USER_TYPE_SUPER){
            list = permissionServiceImpl.list(queryWrapper);
        }else{
            //根据用户ID+角色+权限去查询

            //根据用户ID查询拥有的rid
            List<Integer> rids = roleServiceImpl.queryUserRoleIdsByUid(user.getId());
            //根据rid查询菜单权限ID 过程中可能会有重复

            //set用来过滤重复的 set中为菜单权限ID
            Set<Integer> set = new HashSet<>();
            for(Integer rid:rids){
               List<Integer> pids =  roleServiceImpl.queryRolePermissionByRid(rid);
               set.addAll(pids);
            }

            if(set!=null&&set.size()>0){
                queryWrapper.in("id",set);
                list = permissionServiceImpl.list(queryWrapper);
            }else{
                list = new ArrayList<>();
            }
        }
        List<TreeNode> nodes = new ArrayList<>();

        for(Permission p :list){
            Integer id=p.getId();
            Integer pid=p.getPid();
            String title=p.getTitle();
            String icon=p.getIcon();
            String href=p.getHref();
            Boolean spread = p.getOpen()==Constast.OPEN_TRUE?true:false;
            nodes.add(new TreeNode(id,pid,title,icon,href,spread));
        }
        //构造层级关系
        List<TreeNode> list2 = TreeNodeBuilder.build(nodes,1);
        return new DataGridView(list2);
    }

    /****************菜单管理开始****************/

    /**
     * 初始化树
     * @param permissionVo
     * @return
     */
    @RequestMapping("loadMenuManagerLeftTreeJson")
    public DataGridView loadMenuManagerLeftTreeJson(PermissionVo permissionVo){
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type","menu");
        List<Permission> list = permissionServiceImpl.list(queryWrapper);
        List<TreeNode> nodes = new ArrayList<>();
        for(Permission permission:list){
            Boolean open = permission.getOpen()==1?true:false;
            nodes.add(new TreeNode(permission.getId(),permission.getPid(),permission.getTitle(),open));
        }
        return  new DataGridView(nodes);
    }

    /**
     * 加载数据表格
     * @param permissionVo
     * @return
     */
    @RequestMapping("loadAllMenu")
    public DataGridView LoadAllMenu(PermissionVo permissionVo){
        IPage<Permission> page = new Page<>(permissionVo.getPage(),permissionVo.getLimit());
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        //只查询菜单
        queryWrapper.eq("type","menu");

        //查询条件
        queryWrapper.like(StringUtils.isNotBlank(permissionVo.getTitle()), "title", permissionVo.getTitle());
        //这里将(id = ? OR pid = ?) 包裹了起来
        if(permissionVo.getId()!=null){
            queryWrapper.and(permissionQueryWrapper ->permissionQueryWrapper.eq("id", permissionVo.getId()).or().eq("pid", permissionVo.getId()));
        }

        queryWrapper.orderByAsc("ordernum");

        permissionServiceImpl.page(page,queryWrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }


    @RequestMapping("addMenu")
    public ResultObj addMenu(PermissionVo permissionVo){
        try {
            permissionVo.setType("menu");//设置添加类型
            permissionServiceImpl.save(permissionVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 删除
     * @param permissionVo
     * @return
     */
    @RequestMapping("deleteMenu")
    public ResultObj deleteMenu(PermissionVo permissionVo){
        try {
            permissionServiceImpl.removeById(permissionVo.getId());
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 判断是否有子节点
     * @param permissionVo
     * @return
     */
    @RequestMapping("checkMenuChildren")
    public Map<String,Object> checkDephasChildren(PermissionVo permissionVo){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(permissionVo.getId()!=null,"pid",permissionVo.getId());
        List<Permission> list = permissionServiceImpl.list(queryWrapper);
        if(list.size()>0){
            map.put("value",true);
        }else{
            map.put("value",false);
        }

        return map;

    }

    @RequestMapping("updateMenu")
    public ResultObj updateMenu(PermissionVo permissionVo){
        try {
            permissionServiceImpl.updateById(permissionVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 初始化排排序码
     * @return
     */
    @RequestMapping("loadMenuMaxOrderNum")
    public Map<String,Object> loadMenuMaxOrderNum(){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<Permission> list = permissionServiceImpl.list(queryWrapper);
        if(list.size()>0){
            map.put("value",list.get(0).getOrdernum()+1);
        }else{
            map.put("value",1);
        }
        return map;
    }

    /****************菜单管理结束****************/
}
